const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

let manifestList = [];
let hotupdateJsonStr = fs.readFileSync("./hotupdate.json").toString();
let hotupdateJson = JSON.parse(hotupdateJsonStr);
console.log("v===", hotupdateJson);
let updateKeysList = hotupdateJson["updateKey"];
let updateVersionList = hotupdateJson["updateVersion"];

let siteUrl = process.argv[2];
console.log("siteUrl=========", siteUrl);
let baseDir = process.argv[3];
console.log("baseDir===", baseDir);
let destDirList = [];

for (let i = 0; i < updateKeysList.length; i++) {
    destDirList[i] = baseDir + updateKeysList[i];
    manifestList[i] = {};
    let tempUrl = siteUrl + "" + updateKeysList[i];
    manifestList[i]["packageUrl"] = siteUrl;
    manifestList[i]["remoteManifestUrl"] = tempUrl + '/project.manifest?t=' + new Date().getTime();
    manifestList[i]["remoteVersionUrl"] = tempUrl + '/version.manifest?t=' + new Date().getTime();
    manifestList[i]["version"] = updateVersionList[i];
    manifestList[i]["assets"] = {};
    manifestList[i]["searchPaths"] = [];
}

function readDir(dir, obj) {
    var stat = fs.statSync(dir);
    if (!stat.isDirectory()) {
        return;
    }
    var subpaths = fs.readdirSync(dir),
        subpath, size, md5, compressed, relative;
    for (var i = 0; i < subpaths.length; ++i) {
        if (subpaths[i][0] === '.') {
            continue;
        }
        subpath = path.join(dir, subpaths[i]);
        stat = fs.statSync(subpath);
        if (stat.isDirectory()) {
            readDir(subpath, obj);
        } else if (stat.isFile()) {
            // Size in Bytes
            size = stat['size'];
            md5 = crypto.createHash('md5').update(fs.readFileSync(subpath)).digest('hex');
            compressed = path.extname(subpath).toLowerCase() === '.zip';

            relative = path.relative(baseDir, subpath);
            relative = relative.replace(/\\/g, '/');
            relative = encodeURI(relative);
            //查看文件md5是否在子游戏中
            // let tempMd5Index = getManifestIndexContainMd5(md5);
            let tempMd5Index = 0;
            if (tempMd5Index == 0) { //子游戏不包含该文件
                obj[relative] = {
                    'size': size,
                    'md5': md5
                };
                if (compressed) {
                    obj[relative].compressed = true;
                }
            } else {
                manifestList[tempMd5Index]["assets"][relative] = {
                    'size': size,
                    'md5': md5
                };
                if (compressed) {
                    manifestList[tempMd5Index]["assets"][relative].compressed = true;;
                }
            }
        }
    }
}

var mkdirSync = function(path) {
    try {
        fs.mkdirSync(path);
    } catch (e) {
        if (e.code != 'EEXIST') throw e;
    }
}

// Iterate assets and src folder
readDir(path.join(baseDir, 'assets'), manifestList[0].assets);
readDir(path.join(baseDir, 'src'), manifestList[0].assets);


for (let i = 0; i < destDirList.length; i++) {
    let destManifest = path.join(destDirList[i], 'project.manifest');
    let destVersion = path.join(destDirList[i], 'version.manifest');
    mkdirSync(destDirList[i]);
    fs.writeFileSync(destManifest, JSON.stringify(manifestList[i]));
    console.log(destManifest + ' successfully generated');
    delete manifestList[i].assets;
    delete manifestList[i].searchPaths;
    fs.writeFileSync(destVersion, JSON.stringify(manifestList[i]));
    console.log(destVersion + ' successfully generated');
}